<!--
 * @Descripttion: 员工导入导出
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-06-17 15:49:11
 * @LastEditors: GW
 * @LastEditTime: 2022-05-14 16:39:54
-->
<template>
    <div>
        <!-- <a-modal v-model="exportVisible" title="导出客户数据文件" centered on-ok="handleok" width="650px">
            <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                <a-radio-group v-model="exportRadioValue">
                    <p>
                        <a-radio value="1">导出所选客户：{{exportValue || 0}}条</a-radio>
                    </p>
                    <p>
                        <a-radio value="2">导出符合条件客户：{{pagination.total || 0}}条</a-radio>
                    </p>
                </a-radio-group>
            </div>
            <template slot="footer">
                <a-button key="submit" type="primary" icon="download" @click="exportCrmData">导出</a-button>
                <a-button key="back" @click="() => (exportVisible = false)" icon="close">取消</a-button>
            </template>
        </a-modal> -->

        <a-modal v-model="importVisible" title="导入员工档案" centered on-ok="handleok" width="650px">
            <div style="margin-left:30px;">

                <div style="font-weight: normal;">
                    <div>
                        第1步：
                        下载员工档案导入模板，<a href="javascript:;" @click="downloadTemplate" style="font-size: 12px;color: blue;">点击下载模板</a>
                    </div>
                    <br>
                    <div>
                        第2步：上传文档
                        <label>
                            <input type="file" id="file" name="file" style="padding-left: 15px;" class="form-file" />
                        </label>
                    </div>
                </div>
                <br>

                <div>
                    <span>第3步:导入资料至</span>
                    <label style="padding-left: 15px;">
                        <input name="Fruit" type="radio" checked />员工档案
                    </label>
                </div>
                <div style="margin-top: 15px;">
                    <p>导入说明</p>
                    <div style="margin-left:20px">
                        <p>1.下载导入模板</p>
                        <p>2.上传存储有员工档案的Excel文件，大小不超过5M</p>
                        <p>3.开始导入</p>
                    </div>
                </div>
            </div>
            <template slot="footer">
                <a-button key="submit" type="primary" @click="importCrm">下一步</a-button>
                <a-button key="back" @click="() => (importVisible = false)">取消</a-button>
            </template>
            <div class="import-modal-mask" v-if="importEnd">
                <a-spin class="loading-content" tip="导入中..." />
            </div>
        </a-modal>

        <a-modal v-model="filedVisible" title="匹配导入字段" centered on-ok="handleok" width="650px">
            <a-spin :spinning="isSpinning" tip="导入中...">
                <div style="margin-left:30px;height: 400px;overflow-y: scroll;">
                    <a-table :columns="filedColumns" :data-source="filedData" :pagination="false" bordered>
                        <template slot="inFiled" slot-scope="text, record">
                            <a-select title="下拉效果" size="small" style="width:80%;height:100%" labelStyle="display: none;" v-model="record.crmCode">
                                <a-select-option v-for="(item,index) in record.inFiled" :key="index" :value="item.code">{{item.name}}</a-select-option>
                            </a-select>
                        </template>
                    </a-table>
                </div>
            </a-spin>

            <template slot="footer">
                <a-button v-show="!isSpinning" key="submit" type="primary" @click="importData">导入</a-button>
                <a-button v-show="!isSpinning" key="back" @click="() => (filedVisible = false)">取消</a-button>
            </template>
        </a-modal>

        <a-modal v-model="resultVisible" title="导入结果" centered on-ok="handleok" width="650px">
            <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                <p>导入成功数：{{impotrResult.successNum || 0}}</p>
                <p>导入失败数：{{impotrResult.failNum || 0}}</p>
                <p>如果您需要导入失败的记录及原因，请点击下载按钮</p>
            </div>
            <template slot="footer">
                <a-button key="submit" type="primary" icon="download" @click="downloadImportResult">下载</a-button>
                <a-button key="back" @click="() => (resultVisible = false)" icon="close">取消</a-button>
            </template>
        </a-modal>

        <!-- <a-modal v-model="exportVisible" title="导出客户数据文件" centered on-ok="handleok" width="650px">
            <div style="margin-left:30px;height: 200px;overflow-y: scroll;">
                <a-radio-group v-model="exportRadioValue">
                    <p>
                        <a-radio value="1">导出所选客户：{{exportValue || 0}}条</a-radio>
                    </p>
                    <p>
                        <a-radio value="2">导出符合条件客户：{{pagination.total || 0}}条</a-radio>
                    </p>
                </a-radio-group>
            </div>
            <template slot="footer">
                <a-button key="submit" type="primary" icon="download" @click="exportCrmData">导出</a-button>
                <a-button key="back" @click="() => (exportVisible = false)" icon="close">取消</a-button>
            </template>
        </a-modal> -->
    </div>
</template>

<script>

import { inventoryModal } from "@/components/PopUpLayer";//各种搜索选择弹窗
import { downloadDemo, importData } from "@/api/hr/inductionManage";//导入导出
import { downloadFailCause } from "@/api/crm/customer";

export default {
    components: {
        inventoryModal
    },
    data () {
        const filedColumns = [
            {
                title: "Excel字段",
                dataIndex: "excelFiled",
                key: "excelFiled",
                align: "left",
                width: 100,
            },
            {
                title: "系统字段",
                dataIndex: "inFiled",
                key: "inFiled",
                align: "left",
                width: 100,
                scopedSlots: { customRender: "inFiled" }
            }
        ];
        //表格 头部 可伸缩
        return {
            importEnd: false,
            FixedConditionKeys: ["crmName", "phonetic"],  //固定的搜索条件的Key
            customRenderCode: ["crmName", "shareType"], //table 使用插槽的列
            importVisible: false, //导入文件弹窗
            filedVisible: false, //字段匹配弹窗
            resultVisible: false, //导入结果弹窗
            excelFiled: [], //excel字段
            impotrResult: {}, //导入结果
            isSpinning: false, //导入加载框
            exportVisible: false, //导出弹窗
            exportValue: 0, //要导出选中的数量
            exportRadioValue: "1", //导出redio值
            crmCheckedDatas: [], //客户选中的数据
            filedColumns,
            filedData: []
        };
    },
    methods: {
        //导出客户数据
        exportCrmData () {
            // const { postData, onOffDefineFields } = this;
            // console.log("客户系统——搜索条件：", onOffDefineFields);
            // postData.dtos = onOffDefineFields;
            // if (this.exportRadioValue == 1) {
            //     if (this.exportValue == 0) {
            //         this.$nlyaToast.toast("请选择要导出的客户", {
            //             title: `错误`,
            //             variant: "danger",
            //             solid: true
            //         });
            //         return false;
            //     }
            //     postData.crmIds = this.selectedKeys;
            // } else {
            //     if (this.pagination.total == 0) {
            //         this.$nlyaToast.toast("没有客户数据不能导出", {
            //             title: `错误`,
            //             variant: "danger",
            //             solid: true
            //         });
            //         return false;
            //     }
            //     postData.crmIds = null;
            // }
            exportSupplierData().then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "员工档案.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
                this.exportVisible = false;
                this.selectedKeys = [];
            });
        },
        //导入(解析导入字段)
        importCrm () {

            //上传execl文件 匹配字段
            //this.$refs["merge-modal"].show();
            const formData = new FormData();
            let excelFile = document.getElementById("file").files[0];
            if (excelFile == null || excelFile.name == "") {
                this.$error({
                    title: "错误提示",
                    content: "文件不能为空"
                });
                return false;
            }

            var AllImgExt = ".xls|.xlsx|";
            var extName = excelFile.name
                .substring(excelFile.name.lastIndexOf("."))
                .toLowerCase();
            if (AllImgExt.indexOf(extName + "|") == -1) {
                this.$error({
                    title: "错误提示",
                    content: "文件格式错误，请上传xls、xxlsx类型文件"
                });
                return false;
            }

            let size = excelFile.size;
            size = size / (1024 * 1024);
            if (size >= 5) {
                this.$error({
                    title: "错误提示",
                    content: "文件过大,不能超过5M"
                });
                return;
            }

            formData.append("file", excelFile);

            this.importEnd = true;
            importData(formData).then(response => {
                if (response.code == 200) {
                    this.importEnd = false;
                    this.importVisible = false;
                    // let exlFiled = response.data.excelFiled;
                    // if (exlFiled == null || exlFiled.length == 0) {
                    //     this.$error({
                    //         title: "错误提示",
                    //         content: "文件没有数据"
                    //     });
                    //     return;
                    // }
                    // this.filedVisible = true;
                    // this.filedModelFooter = true;
                    if (response.code == 200) {
                        this.impotrResult = response.data;
                        this.resultVisible = true;
                        this.filedVisible = false;
                        this.isSpinning = false;
                        // this.PageList();
                        //刷新父组件数据
                        this.$emit('syncFun');
                    } else {
                        this.importEnd = false;
                        this.filedVisible = false;
                        this.isSpinning = false;
                        // this.$message.error("导入失败，请联系管理员");
                    }
                }
            }).catch(res => {
                this.importEnd = false;
            });
        },
        //下载模版
        downloadTemplate () {
            downloadDemo().then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "导入员工档案模板.xls");
                document.body.appendChild(link);
                link.click();
            });
        },
        //导入数据
        importData () {
            this.isSpinning = true;
            this.filedModelFooter = false;
            let crmCodes = this.filedData.map(f => f.crmCode);
            console.log(crmCodes);
            const formData = new FormData();
            formData.append("file", document.getElementById("file").files[0]);
            let excelArray = this.filedData.map(f => f.excelFiled);;

            console.log(excelArray)
            formData.append("excelFiled", this.excelFiled);
            formData.append("dbFiled", crmCodes);
            formData.append("classId", this.inventoryId);
            importData(formData).then(response => {
                if (response.code == 200) {
                    this.impotrResult = response.data;
                    this.resultVisible = true;
                    this.filedVisible = false;
                    this.isSpinning = false;
                    this.pageList();
                    //刷新父组件数据
                    this.$emit('syncFun');
                } else {
                    this.filedVisible = false;
                    this.isSpinning = false;
                    this.$message.error("导入失败，请联系管理员");
                }
            });
        },
        //下载导入结果
        downloadImportResult () {
            console.log("下载导入结果", this.impotrResult);
            const formData = new FormData();
            formData.append("excelField", this.impotrResult.excelField);
            formData.append("failCause", this.impotrResult.failCause);
            formData.append("failData", JSON.stringify(this.impotrResult.failData));
            downloadFailCause(formData).then(response => {
                let url = window.URL.createObjectURL(
                    new Blob([response], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", "导入失败的数据和原因.xls");
                document.body.appendChild(link);
                link.click();
                this.resultVisible = false;
            });
        },
        //导入弹窗
        importFile () {
            this.importVisible = true;

            this.$nextTick(() => {
                let file = document.getElementById("file");
                if (file.outerHTML) {
                    file.outerHTML = file.outerHTML;
                } else {      //FF
                    file.value = "";
                }
            })
        },
    }
};
</script>
<style lang="less">
    .import-modal-mask {
        position: fixed;
        width: 100%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        height: 100%;
        z-index: 1000;
        background: rgba(0, 0, 0, 0.4);

        .loading-content {
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -28px;
            // margin-left: 100px;
            font-size: 14px;
            color: #fff;
            .ant-spin-dot {
                font-size: 60px;
            }
            .ant-spin-dot i {
                width: 30px;
                height: 30px;
                background: #fff;
            }
        }
    }
</style>
